 #!/usr/bin/python
 # -*- coding: utf-8 -*-


# Echo server program
import socket
import os
import sys

HOSTLISTEN = ''                 # Symbolic name meaning the local host
HOSTSEND = ''		# will be given the ip of firewall	
PORTLISTEN = 9870              # Arbitrary non-privileged port between bbw1 and server agent
PORTSEND = 8760 # port between serveragent and firewallagent

data = None

while 1:

	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
	s.bind((HOSTLISTEN, PORTLISTEN))
	s.listen(1)
	conn, addr = s.accept()
	print 'Connected by', addr
	while 1:
		if not data: 
			#print "burada"
			data = conn.recv(1024)	# recv from java application
			#print data
	    		if not data: break
	    		conn.send("OK")	# send the data received to the java application
			conn.close()
	    		li=data.split(',')
			print "Message: ", "protokol", li[0].strip(), "source", li[1].strip(), "source port", li[2].strip(), "destination", li[3].strip(), "destination port", li[4].strip(), "action", li[5].strip()
			
		else:
		
	    		try: # try till there is a connection to the firewall port and keep the received data
	    			ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
				#ss.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
	    			ss.connect((HOSTSEND, PORTSEND))
				
				#print "connect oldu"
	
	    		except:
				#print sys.exc_info()[0]
				if data:
					#print "girdi" 
					continue
				
			#print "ok"
	    		ss.send(",".join(li))	# send to the firewall agent
	    		data = ss.recv(1024)		# accept from firewall agent
	    		#ss.shutdown(2)
			ss.close()
	    		print repr(data)
	    		print "..."
			
			data= None
			break
			
			
	
	conn.close()

	
	ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	ss.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
	while True:
		try:
			ss.bind((HOSTSEND, PORTSEND))
			ss.listen(1)
			conn, addr = ss.accept()
			break
		except:
			continue
	
	#print "bura"
	while 1:
		data = conn.recv(1024) ## receive the port number
		if data: print "Port number received: ", repr(data)
		if not data: break
		conn.send(data)
		ss.close()